//
//  WEIBOAccountTool.m
//  OneWeiBo
//
//  Created on 9.
//   
//

#import "WEIBOAccountTool.h"
#import "WEIBOAccount.h"
#import "WEIBOHttpTool.h"

@implementation WEIBOAccountTool

+ (NSString *)accountFilePath
{
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *saveFile = [doc stringByAppendingPathComponent:@"account.data"];
    return saveFile;
}

// 保存账号信息
+ (void)saveAccount:(WEIBOAccount *)account
{
//    NSDate *curData = [NSDate date];
//    account.expiresTime = [curData dateByAddingTimeInterval:1000000];
    
    // 归档
    [NSKeyedArchiver archiveRootObject:account toFile:[self accountFilePath]];
}

// 获取账号信息
+ (WEIBOAccount *)account
{
    //取出账号
    WEIBOAccount *account = [NSKeyedUnarchiver unarchiveObjectWithFile:[self accountFilePath]];
    NSDate *curData = [NSDate date];
    // 比较是否过期
//    if ([curData compare:account.expiresTime] == NSOrderedAscending) {
        return account;
//    }else {
//        return nil;
//    }
}

+ (void)accessTokenWithCode:(NSString *)code success:(void (^)())success failure:(void (^)(NSError *))failure
{
    // 封装请求参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"client_id"] = WEIBOAppKey;
    params[@"client_secret"] = WEIBOAppSecret;
    params[@"grant_type"] = @"authorization_code";
    params[@"code"] = code;
    params[@"redirect_uri"] = WEIBORedirectUrl;
    
    // 发生请求
    [WEIBOHttpTool postWithURL:@"https://api.weibo.com/oauth2/access_token" params:params success:^(id json) {
        //WEIBOLog(@"accessToken请求成功：%@",json);
        // 将字典转位模型
        WEIBOAccount *account = [WEIBOAccount accountWithDic:json];
        
        // 归档
        [WEIBOAccountTool saveAccount:account];
        
        if (success) {
            success();
        }
        
    } failure:^(NSError *error) {
        if (failure) {
            failure(error);
        }
    }];

}

@end
